import 'dart:collection';
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/AppConfig/Config.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';

import '../AppConfig/CityLIstData.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../Message/MessageCenter.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'UpEmptyLine.dart';

class AddLine extends StatefulWidget {
  const AddLine({super.key, required this.linesNum});
  final String linesNum;
  @override
  State<AddLine> createState() => _AddLineState();
}

class _AddLineState extends State<AddLine> {
  late String startCity="+ 选择";
  late String endCity="+ 选择";
  List chooseStartList=[];
  List chooseEndList=[];
  int startType=-1;
  int endType=-1;
  List startNameList=[];
  List endNameList=[];
  List startCodeList=[];
  List endCodeList=[];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "添加常跑路线",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [

          Badge(
            // label:Text("1"),
            child:GestureDetector(
              child: Row(
                children: [
                  Image.asset("lib/Images/RoadLine/消息icon.png",width: 16.w,height: 16.h,),
                  SizedBox(width: 10.w,),
                ],
              ),
              onTap: (){
                Navigator.push( context, FadeRoute(page:MessageCenter()));
              },
            ),

          ),
        ],
      ),
    body: ListView(
      children: [
        SizedBox(height: 8.h,),
        Container(
          // height: 60.h,
          padding: EdgeInsets.only(bottom: 8.h),
          margin: EdgeInsets.all(8.w),

          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child:Column(
           crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 8.h,),
              Row(

                children: [
                  SizedBox(width: 18.w,),
                  Text("我的配货路线",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                  SizedBox(width: 4.w,),
                  Text("("+widget.linesNum+"/10)",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                ],
              ),
              SizedBox(height: 4.h,),
              Row(
                children: [
                  SizedBox(width: 18.w,),
                  Image.asset("lib/Images/RoadLine/添加线路icon.png",width: 15.w,height: 13.h,),
                  SizedBox(width: 8.w,),
                  Text("添加线路，货源第一时间提醒您",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontSize: 12.sp),),

                ],
              ),
            ],
          
            
          ),
        ),
        SizedBox(height: 2.h,),
        Container(
         padding: EdgeInsets.only(bottom: 8.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 8.h,),
              Row(
                children: [
                  SizedBox(width: 18.w,),
                  Image.asset("lib/Images/RoadLine/绿色圆圈.png",height: 9.h,width: 9.w,),
                  SizedBox(width: 4.w,),
                  Text("请选择装货地",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                ],
              ),
              SizedBox(height: 8.h,),
              GestureDetector(
                child:  Container(
                  margin: EdgeInsets.only(left: 18.w),
                  padding: EdgeInsets.only( right: 10.w,left: 10.w,top: 5.h,bottom: 5.h),
                  width:70.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                      color:startCity!="+ 选择"?Color.fromRGBO(251, 236, 228, 1) :Color.fromRGBO(240, 240, 240, 1),
                      borderRadius: BorderRadius.all(Radius.circular(5))),
                  child:Center(
                    child:   Text(startCity,style: TextStyle(color: startCity!="+ 选择"?MyColors.themeColor: Colors.black,fontSize: 13.sp,fontWeight: FontWeight.w400),),
                  ),

                ),
                onTap: ()async{

                  final result = await showModalBottomSheet(
                      context: context,
                      isScrollControlled: true,

                      builder: (BuildContext context) {
                        return ChooseAddressSheet(addressType: 1,

                        );
                      }
                  );
                  if (result != null) {
                    setState(() {

                      startCity=result[0];
                      startType=result[1];
                      startNameList=[result[2],result[3],result[4]];
                      print(startNameList);
                      for (String cityName in startNameList) {
                        String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                        if (cityCode != "") {
                          print('$cityName 的城市编码为：$cityCode');
                          cityCode=getCodeResult(cityCode);
                          startCodeList.add(cityCode);

                        } else {
                          print('未找到城市 $cityName');
                        }
                      }
                    });
                  }


                },
              ),
              SizedBox(height: 8.h,),
              Container(
                margin: EdgeInsets.only(right: 8.w),
                height: 1.h,color: Color.fromRGBO(248, 248, 248, 1),),
              SizedBox(height: 8.h,),
              Row(
                children: [
                  SizedBox(width: 18.w,),
                  Image.asset("lib/Images/RoadLine/红色圆圈.png",height: 9.h,width: 9.w,),
                  SizedBox(width: 4.w,),
                  Text("请选择卸货地",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                ],
              ),
              SizedBox(height: 8.h,),
              GestureDetector(
                child:  Container(
                  margin: EdgeInsets.only(left: 18.w),
                  padding: EdgeInsets.only( right: 10.w,left: 10.w,top: 5.h,bottom: 5.h),
                  width:70.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                      color:endCity!="+ 选择"?Color.fromRGBO(251, 236, 228, 1) :Color.fromRGBO(240, 240, 240, 1),
                      borderRadius: BorderRadius.all(Radius.circular(5))),
                  child:Center(
                    child:   Text(endCity,style: TextStyle(color: endCity!="+ 选择"?MyColors.themeColor: Colors.black,fontSize: 13.sp,fontWeight: FontWeight.w400),),
                  ),
                ),
                onTap: ()async{

                  final result = await showModalBottomSheet(
                      context: context,
                      isScrollControlled: true,

                      builder: (BuildContext context) {
                        return ChooseAddressSheet(addressType: 2,

                        );
                      }
                  );
                  if (result != null) {
                    setState(() {
                      endCity=result[0];
                      endType=result[1];
                      endNameList=[result[2],result[3],result[4]];
                      print(endNameList);
                      for (String cityName in endNameList) {
                        String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                        if (cityCode != "") {
                          print('$cityName 的城市编码为：$cityCode');
                          cityCode=getCodeResult(cityCode);
                          endCodeList.add(cityCode);

                        } else {
                          print('未找到城市 $cityName');
                        }
                      }
                    });
                  }



                },
              ),
              SizedBox(height:38.h ,),
              Container(
                  height: 35.h ,
                  margin: EdgeInsets.only(left: 30.w,right: 30.w),
                  decoration: BoxDecoration(
                      color: Color.fromRGBO(231, 112, 27, 0.85),
                      borderRadius: BorderRadius.all(Radius.circular(30))),

                  width: double.infinity,


                  child: TextButton(
                    child: Text("添加",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                    onPressed: () async {
                      if(startNameList.isEmpty){
                        BrnToast.show("请选择装货城市", context);
                      }else if(endNameList.isEmpty){
                        BrnToast.show("请选择卸货城市", context);
                      }else  if(startNameList[1]==""){
                        BrnToast.show("装货地请至少选择至市", context);
                      }else if(endNameList[1]==""){
                        BrnToast.show("卸货地请至少选择至市", context);
                      }else{
                        String? drvId =await UserIdManager.getUserID();
                        ApiManager.postData(
                          context,
                          'api/goods/driver/route/add',
                          {
                            "driverId":drvId,
                            "loadPlace": {
                              "province": startNameList[0],
                              "city": startNameList[1],
                              "county": startNameList[2],
                              "areaCode": startCodeList.last,
                            },
                            "unloadPlace": {
                              "province": endNameList[0],
                              "city": endNameList[1],
                              "county": endNameList[2],
                              "areaCode":endCodeList.last,
                            },
                          },
                              (responseData) {
                            setState(() {
                              BrnToast.show("添加成功", context);
                              Navigator.pop(context,"success");
                            });
                          },
                        );
                      }
                    },
                  )
              ),
            ],
          ),
        ),
      ],
    ),
    );
  }
}



